/*package com.hama.iotrust.common.mvc;

import com.hama.iotrust.common.Constants;
import com.hama.iotrust.common.SessionConstants;
import com.hama.iotrust.common.mybatis.criteria.Criteria;
import com.hama.iotrust.common.mybatis.criteria.ExpressionFactory;
import com.hama.iotrust.common.util.SpringContextHolder;
import com.hama.iotrust.common.util.StrUtil;
import com.hama.yixun.resources.entity.Resources;
import com.hama.yixun.resources.mapper.ResourcesMapper;
import com.hama.yixun.roleResource.entity.RoleResource;
import com.hama.yixun.roleResource.mapper.RoleResourceMapper;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SecurityFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 4731865507572808910L;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(SecurityFilter.class);

	private String contextPath;

	private transient AntPathMatcher urlMatcher = new AntPathMatcher();

	private int _tokenResetTime = 15;

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		ServletContext application = httpRequest.getSession()
				.getServletContext();
		Map<String, String> map = new HashMap<String, String>();// 把资源地址和对应的角色id放在map里面

		String requestURI = httpRequest.getRequestURI();
		requestURI = requestURI.substring(contextPath.length());
		if (!requestURI.startsWith("/")) {
			requestURI = "/" + requestURI;
			requestURI = requestURI.split("?")[0];
		}
		System.out.println(requestURI);
		// TokenService tokenService =
		// SpringContextHolder.getBean(TokenService.class);
		// // final Identity identity =
		// SpringContextHolder.getBean(Identity.class);
		// String tokenString = null;
		// Long userId = null;
		// final Cookie[] mycookies = httpRequest.getCookies();
		// if (mycookies != null) {
		// for (int i = 0; i < mycookies.length; ++i) {
		// if ("token".equalsIgnoreCase(mycookies[i].getName())) {
		// tokenString = mycookies[i].getValue();
		// Criteria<Token> criteria = Criteria
		// .create(Token.class);
		// SimpleExpression simpleExpression = ExpressionFactory.eq("token",
		// tokenString);
		// criteria.add(simpleExpression);
		// Token token = tokenService.GetToken(tokenString);
		// if (token == null) {
		//
		// } else {
		// if (!isTokenValid(token)) {
		//
		// } else {
		// token.setBegindate(new Date());
		// tokenService.update(token);
		// userId = token.getUserId();
		// //request.getParameterMap().put("userId", new String[]
		// {userId.toString()});
		// request.setAttribute("userId", userId);
		// //httpRequest.
		// request.setAttribute("erpAccountId", token.getErpAccountId());
		//
		// // BindAccount account = new BindAccount();
		// // account.setErpAccountId(token.getErpAccountId());
		// // account.setPersonAccountId(userId);
		// // request.setAttribute("account", account);
		// // request.setAttribute(arg0, arg1);
		// }
		// }
		// }
		// }
		// }
		if (isExclusion(requestURI)) {
			chain.doFilter(request, response);
			return;
		}
		// if(userId == null) {
		// unauthorized(httpRequest, httpResponse);
		// return;
		// }

		httpRequest.setAttribute(
				SessionConstants.SESSION_ORGANIZATION_ACCOUNT,
				httpRequest.getSession().getAttribute(
						SessionConstants.SESSION_ORGANIZATION_ACCOUNT));
		httpRequest.setAttribute(
				SessionConstants.SESSION_ORGANIZATION,
				httpRequest.getSession().getAttribute(
						SessionConstants.SESSION_ORGANIZATION));
		httpRequest.setAttribute(
				SessionConstants.SESSION_PERSON_ACCOUNT,
				httpRequest.getSession().getAttribute(
						SessionConstants.SESSION_PERSON_ACCOUNT));
		httpRequest.setAttribute(
				SessionConstants.SESSION_PLATFORM_ACCOUNT,
				httpRequest.getSession().getAttribute(
						SessionConstants.SESSION_PLATFORM_ACCOUNT));
		httpRequest.setAttribute(SessionConstants.SESSION_PERSON, httpRequest
				.getSession().getAttribute(SessionConstants.SESSION_PERSON));

		httpRequest.setAttribute(
				SessionConstants.SESSION_TEACHER_ACCOUNT,
				httpRequest.getSession().getAttribute(
						SessionConstants.SESSION_TEACHER_ACCOUNT));
		httpRequest.setAttribute(SessionConstants.SESSION_TEACHER, httpRequest
				.getSession().getAttribute(SessionConstants.SESSION_TEACHER));
		
		//value==0为机构端,1平台端,2为APP端
		int value = Integer.parseInt(application.getInitParameter("webAccess"));
		String NOLoginApp=application.getInitParameter("NOLoginApp");
		String NOLoginOrg=application.getInitParameter("NOLoginOrg");
		String NOLoginPlat=application.getInitParameter("NOLoginPlat");
		
//		switch (value) {
//		case Constants.WEB_ID_PLAT:
//			if (httpRequest
//					.getAttribute(SessionConstants.SESSION_PLATFORM_ACCOUNT) == null) {
//
//				if (NOLoginPlat.indexOf(requestURI) != -1) {
//					chain.doFilter(request, response);
//					return;
//				} else {
//					if (httpRequest.getHeader("x-requested-with") != null
//							&& httpRequest.getHeader("x-requested-with")
//									.equals("XMLHttpRequest")) {
//						httpResponse.setHeader("sessionstatus", "1");
//					} else {
//						httpResponse.sendRedirect(httpRequest.getContextPath()+Constants.PLAT_LOGINURL);
//						return;
//					}
//				}
//
//			} else {
//				chain.doFilter(request, response);
//				return;
//			}
//		case Constants.WEB_ID_ORG:
//			if (httpRequest
//					.getAttribute(SessionConstants.SESSION_ORGANIZATION_ACCOUNT) == null) {
//
//				if (NOLoginOrg.indexOf(requestURI) != -1) {
//					chain.doFilter(request, response);
//					return;
//				} else {
//					if (httpRequest.getHeader("x-requested-with") != null
//							&& httpRequest.getHeader("x-requested-with")
//									.equals("XMLHttpRequest")) {
//						httpResponse.setHeader("sessionstatus", "0");
//					} else {
//						
//						httpResponse.sendRedirect(httpRequest.getContextPath()+Constants.ORG_LOGINURL);
//						return;
//					}
//				}
//
//			} else {
//				chain.doFilter(request, response);
//				return;
//			}
//
//		case Constants.WEB_ID_APP:
//
//			if (httpRequest
//					.getAttribute(SessionConstants.SESSION_PERSON_ACCOUNT) == null) {
//				if (NOLoginApp.indexOf(requestURI) != -1) {
//					chain.doFilter(request, response);
//					return;
//				} else {
//					httpResponse.getOutputStream().print("{\"result\":"+Constants.SESSION_TIMEOUT_RESULT+"}");
//					return;
//				}
//
//			} else {
//				chain.doFilter(request, response);
//				return;
//			}
//		}
		chain.doFilter(request, response);
		return;
	}

	// public boolean isTokenValid(Token token) {
	// if (token != null) {
	// long newTokenDate = System.currentTimeMillis();
	// long tokenBeginDate = token.getBegindate().getTime();
	// long valideTime = _tokenResetTime * 60 * 1000;
	// if (newTokenDate - tokenBeginDate <= valideTime) {
	// return true;
	// }
	// }
	// return false;
	// }
	public void init(FilterConfig config) throws ServletException {
		this.contextPath = getContextPath(config.getServletContext());
	}

	private String getContextPath(ServletContext context) {
		String contextPath = context.getContextPath();

		if (contextPath == null || contextPath.length() == 0) {
			contextPath = "/";
		}

		return contextPath;
	}

	public boolean isExclusion(String requestURI) {
		if (requestURI.equals("/")) {
			return true;
		}
		PermissionsSource permissionsSource = SpringContextHolder
				.getBean(PermissionsSource.class);
		Set<String> excludesPattern = permissionsSource.getExclusions();
		if (excludesPattern == null) {
			return false;
		}
		for (String pattern : excludesPattern) {
			if (urlMatcher.match(pattern, requestURI)) {
				return true;
			}
		}
		return false;
	}

	private void unauthorized(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
		} else {
			request.getRequestDispatcher("/login.do")
					.forward(request, response);
		}
	}

	private void writeError(HttpServletRequest request,
			HttpServletResponse response, String message) throws IOException,
			ServletException {
		if (request.getHeader("accept").indexOf("application/json") > -1
				&& "XMLHttpRequest".equals(request
						.getHeader("X-Requested-With"))) {
			try {
				String contentType = "application/json";
				response.setContentType(contentType);
				response.setCharacterEncoding("UTF-8");
				Map<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("result", 0);
				jsonMap.put("message", message);
				String json = StrUtil.jsonFromObject(jsonMap);
				response.getWriter().print(json);
				response.getWriter().flush();
				response.getWriter().close();
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
			}
		} else {
			request.setAttribute("exception", message);
			request.getRequestDispatcher("/error.jsp").forward(request,
					response);
		}
	}

	*//**
	 * 权限设置
	 * 
	 * @param application
	 * @param map
	 * @param requestURI
	 * @param httpRequest
	 *//*
	private boolean checkRole(ServletContext application,
			Map<String, String> map, String requestURI,
			HttpServletRequest httpRequest) {
		try {
			if (application.getAttribute("map") == null) {
				SqlSessionFactory factory = SpringContextHolder
						.getBean("sqlSessionFactory");
				SqlSession session = factory.openSession();
				Criteria<Resources> cri_res = Criteria.create(Resources.class);
				ResourcesMapper mapper_res = session
						.getMapper(ResourcesMapper.class);
				RoleResourceMapper mapper_role = session
						.getMapper(RoleResourceMapper.class);
				List<Resources> list_res = mapper_res.selectByCriteria(cri_res);
				for (Resources resources : list_res) {
					Criteria<RoleResource> criteria = Criteria
							.create(RoleResource.class);
					String key = resources.getUrl();
					criteria.add(ExpressionFactory.eq("resourceid",
							resources.getId()));
					List<RoleResource> list = mapper_role
							.selectByCriteria(criteria);
					StringBuilder sb = new StringBuilder();
					for (RoleResource roleResource : list) {
						sb.append(roleResource.getRoleid());
					}
					String value = sb.toString();
					map.put(key, value);
				}
				session.close();
				application.setAttribute("map", map);
				String ids = map.get(requestURI);
				String id = (String) httpRequest.getSession().getAttribute(
						SessionConstants.SESSION_ROLE);// 从session中获取用户角色id
				// 游客登录
				if (StrUtil.isEmpty(id)) {
					id = "5";
				}
				if (ids.indexOf(id) == -1) {
					return false;
				}
			} else {
				map = (Map<String, String>) application.getAttribute("map");
				String ids = map.get(requestURI);
				String id = (String) httpRequest.getSession().getAttribute(
						SessionConstants.SESSION_ROLE);// 从session中获取用户角色id
				// 游客登录
				if (StrUtil.isEmpty(id)) {
					id = "5";
				}
				if (ids.indexOf(id) == -1) {
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}
*/